<script setup lang="ts">
import { type Ref, onMounted, computed } from 'vue'
import useAiPptStore from '@/stores/ai_ppt'
import AIAvatar from '@/icons/AIAvatar.vue'
import Pagination from '@/components/pagination/index.vue'
import PptHeader from './PptHeader.vue'
import { useRouter, type Router } from 'vue-router'
import { storeToRefs } from 'pinia'
import PptCover from '@/components/ppt-cover/index.vue'
import { pptOutlineKey, pptThemeInputKey, pptFileIdKey, pptFileContentKey } from './ppt-helpers'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { PPTListItem } from '@/models/ai-ppt'
import { MessageBoxInputData } from 'element-plus/es/components/message-box/src/message-box.type'
import { httpRestore, httpSavePptData } from '@/api/ai-ppt'

const { getPptList, deletePpt } = useAiPptStore()
const { searchQuery, pptList, pptTotal } = storeToRefs(useAiPptStore())
const router: Router = useRouter()

const tabIndex: Ref<number> = computed(() => {
  return searchQuery.value.type === 1 ? 0 : 1
})

onMounted(() => {
  if (!pptList.value.length) {
    handleGetPptList()
  }
})

const handleGetPptList = async () => {
  const loading = ElLoading.service({fullscreen: true})
  await getPptList()
  loading.close()
}

const changeTabIndex = async (index: number) => {
  if (tabIndex.value === index) {
    return
  }
  // tabIndex.value = index
  if (index === 0) {
    searchQuery.value.type = 1
  } else {
    searchQuery.value.type = 0
  }
  searchQuery.value.page = 1
  await handleGetPptList()
}

const goPath = (path: string) => {
  window.sessionStorage.removeItem(pptOutlineKey.value)
  window.sessionStorage.removeItem(pptThemeInputKey.value)
  window.sessionStorage.removeItem(pptFileIdKey.value)
  window.sessionStorage.removeItem(pptFileContentKey.value)
  router.push(path)
}

const goContent = (id: number) => {
  if (tabIndex.value === 1) {
    return
  }
  router.push({
    path: '/ai-ppt/generate-ppt',
    query: { id },
  })
}

const handleDeletePpt = async (id: number, type: number = 1) => {
  const message: string = type === 1 ? '删除内容将进入回收站，30天后自动彻底删除。' : '确认彻底删除，删除后无法找回。'
  const confirm: boolean = await ElMessageBox.confirm(message, '确认删除？')
    .then(() => true).catch(() => false)
  if (!confirm) return
  const result = await deletePpt(id, type)
  if (result) {
    ElMessage.success('删除成功')
  }
}

const handleUpdateTitle = async (item: PPTListItem): Promise<void> => {
  const prompt: MessageBoxInputData | null = await ElMessageBox.prompt('请输入备注内容', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputValue: item.ppt_name,
    inputErrorMessage: '请输入名称',
  }).catch(() => null)
  if (!prompt) {
    return
  }
  const { value } = prompt
  const result = await httpSavePptData(item.id, value, '', '').then(() => true).catch(() => false)
  if (result) {
    ElMessage.success('修改成功')
    item.ppt_name = value
  }
}

const handleRestore = async (id: number) => {
  const res = await httpRestore(id).then(() => true).catch(() => false)
  if (res) {
    ElMessage.success('修改成功')
    await handleGetPptList()
  }
}

</script>

<template>
  <ppt-header title="AI PPT" />
  <div class="padding-lr-30 padding-bottom-30 padding-top-10">
    <div class="font-size-2xl font-bold line-height-3xl ppt-tab active">快速创建</div>
    <div class="flex align-items-center gap-30">
      <div
        class="padding-20 font-bold line-height-2xl border-radius-xl w-240 h-150 btn-ppt"
        @click="goPath('/ai-ppt/generate-outline')"
      >
        <span>智能生成PPT</span>
        <div class="btn-icon">
          <el-icon>
            <AIAvatar />
          </el-icon>
        </div>
      </div>
      <div
        class="padding-20 font-bold line-height-2xl border-radius-xl w-240 h-150 btn-ppt next"
        @click="goPath('/ai-ppt/choose-template')"
      >
        <span>选择模板创建PPT</span>
        <div class="btn-icon next">PPT</div>
      </div>
    </div>
    <div class="flex align-items-center gap-30 margin-top-30">
      <div
        class="font-size-2xl font-bold line-height-3xl pointer ppt-tab"
        :class="tabIndex === 0 ? 'active' : ''"
        @click="changeTabIndex(0)"
      >历史作品
      </div>
      <div
        class="font-size-2xl font-bold line-height-3xl pointer ppt-tab"
        :class="tabIndex === 1 ? 'active' : ''"
        @click="changeTabIndex(1)"
      >回收站
      </div>
    </div>
    <div class="flex gap-30 flex-warp">
      <div class="flex h-400 pw-100 justify-content-center align-items-center" v-if="pptList.length === 0">
        <el-empty description="暂无作品" />
      </div>
      <div
        v-for="item in pptList"
        class="ppt-item pointer"
        @click="goContent(item.id)"
      >
        <ppt-cover :images="item.ppt_image ? JSON.parse(item.ppt_image) : []" />
        <div class="flex justify-content-between align-items-center padding-lr-10 title gap-10">
          <div class="multi-line-text">{{ item.ppt_name }}</div>
          <div class="more flex align-items-center justify-content-center" @click.stop="() => {}">
            <el-dropdown placement="bottom" trigger="click">
              <el-icon>
                <component is="MoreFilled" />
              </el-icon>
              <template #dropdown>
                <el-dropdown-item v-if="tabIndex === 0" @click="handleUpdateTitle(item)">
                  <el-icon>
                    <component is="Edit" />
                  </el-icon>
                  重命名
                </el-dropdown-item>
                <el-dropdown-item v-if="tabIndex === 0" @click="handleDeletePpt(item.id)">
                  <el-icon>
                    <component is="Delete" />
                  </el-icon>
                  删除作品
                </el-dropdown-item>
                <el-dropdown-item v-if="tabIndex === 1" @click="handleDeletePpt(item.id, 2)">
                  <el-icon>
                    <component is="Delete" />
                  </el-icon>
                  彻底删除
                </el-dropdown-item>
                <el-dropdown-item v-if="tabIndex === 1" @click="handleRestore(item.id)">
                  <el-icon>
                    <component is="Check" />
                  </el-icon>
                  恢复
                </el-dropdown-item>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </div>
    <pagination
      :total="pptTotal"
      v-model:limit="searchQuery.limit"
      v-model:page="searchQuery.page"
      @pagination="handleGetPptList"
    />
  </div>
</template>

<style scoped lang="scss">
.btn-ppt {
  color: var(--el-color-white);
  background: radial-gradient(circle at top left, rgb(229, 188, 145), rgb(212, 134, 160), rgb(193, 73, 183));
  position: relative;
  cursor: pointer;

  &.next {
    background: radial-gradient(circle at top left, rgb(212, 134, 160), rgb(241, 171, 102));
  }

  .btn-icon {
    background: rgba(66, 136, 216, 0.6);
    width: 70px;
    height: 70px;
    border-radius: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 38px;
    color: rgba(255, 255, 255, 0.6);
    position: absolute;
    right: 10px;
    bottom: 5px;

    &.next {
      background: rgba(66, 136, 216, 0.8);
      border-radius: 6px;
      font-size: 36px;
      color: rgb(241, 171, 102);
    }
  }
}

.ppt-tab {
  color: #999;

  &.active {
    color: #111;
  }
}

.ppt-item {
  box-shadow: var(--el-box-shadow);
  border-radius: 6px;
  width: 300px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.8);

  .img {
    width: 100%;
    height: calc(100% - 40px);
    font-size: 80px;
    color: #ABABAB;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .title {
    border-top: 1px solid #DEDEDE;
    height: 40px;
    color: var(--el-text-color-primary);

    .more {
      cursor: pointer;
      font-size: 24px;
      height: 24px;
      color: var(--el-text-color-regular);
    }
  }
}
</style>